package bankservice.endpoint;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class ServerListener extends Thread{
	
	private int serverPortNumber;
	private BankImpl destinationBank;
 
	public ServerListener(BankImpl bank,int portNumber ) {
		
		serverPortNumber = portNumber;		
		destinationBank = bank;	
   	}
	
	public void run() {
		
		DatagramSocket aSocket = null;
		
		try{
			// create socket at agreed port
	    	aSocket = new DatagramSocket(serverPortNumber);
		
			byte[] buffer = new byte[1000];
			
			byte[] replyData ;
			int replyDataLength ;
			
			String packetData;
			
			System.out.println("Server starts to listen on port " + serverPortNumber);
			
			while(true){
				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(request);
				
				replyData = request.getData();
				replyDataLength = request.getLength();
				
				packetData = new String(request.getData());
				
				String accIndex = packetData.substring(2,5);
				int accountIndex = Integer.parseInt(accIndex);
								
				if ((accountIndex<=0 )||(accountIndex>20)){
					
					String  data = "ERROR";
					replyData = data.getBytes();					
					
					DatagramPacket reply = new DatagramPacket(replyData, 5, request.getAddress(),					
							request.getPort());
					
					aSocket.send(reply);
				}
				else{
				
					String destinationAccountNumber = packetData.substring(0,5);
				
					Float depositeAmount = new Float(packetData.substring(5));
				
					DatagramPacket reply = new DatagramPacket(request.getData(), request.getLength(), request.getAddress(),
				
						request.getPort());
								
					destinationBank.deposite(destinationAccountNumber, depositeAmount);				
					
					aSocket.send(reply);
				}
								
			}
		}catch (SocketException e){System.out.println("Socket Error: " + e.getMessage());
		}catch (IOException e) {System.out.println("IO Error: " + e.getMessage());
		}finally {if(aSocket != null) aSocket.close();}
	}

}
